﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using XWord.WPF.ApplicationFramework.Threads;

namespace XWord.WPF.ApplicationFramework
{
    public class TextBoxService
    {


        public static bool GetEnterLine(DependencyObject obj)
        {
            return (bool)obj.GetValue(EnterLineProperty);
        }

        public static void SetEnterLine(DependencyObject obj, bool value)
        {
            obj.SetValue(EnterLineProperty, value);
        }

        public static readonly DependencyProperty EnterLineProperty =
            DependencyProperty.RegisterAttached("EnterLine", typeof(bool), typeof(TextBoxService),
            new UIPropertyMetadata(false, (o, a) =>
            {
                var element = o as TextBox;
                element.KeyUp += new System.Windows.Input.KeyEventHandler((obj, args) =>
                {
                    UIThread.BeginInvoke(() =>
                    {
                        if (args.Key == Key.Enter)
                        {
                            int line = element.SelectionStart;
                            var start = element.Text.Substring(0, line);
                            var end = string.Empty;
                            if (element.Text.Length > line)
                            {
                                end = element.Text.Substring(line);
                            }
                            element.Text = start + Environment.NewLine + end;
                            element.SelectionStart = line + 1;
                        }
                    });

                });
            }));

    }
}
